<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    <div v-loading="loadingRef">
      <BasicForm @register="registerForm" />
    </div>
  </PageWrapper>
</template>

<script lang="ts"
  setup>
  import { ref, h } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { addClassifyDevice } from '@/api/collection/classify/index';
  import { BasicForm, useForm } from '@/components/Form'
  import { FormSchema } from '@/components/Table'

  import {
    getDevicePropertyDataTypeList,
    getDeviceList,
    getDeviceTypeList,
  } from '@/api/collection/device'
  import { getClassifyTree } from '@/api/collection/classify';
  import { Modal, message } from 'ant-design-vue';
  // import { deviceData } from './configData'

  defineOptions({ name: 'ClassifyManageConfig' });
  const deviceNameData = ref<any[]>([])
  const dataTypeData = ref<any[]>([])
  const loadingRef = ref(false)

  const handleChangeType = async (id, data) => {
    dataTypeData.value = []
    // 设备名称
    loadingRef.value = true
    // TODO 电表数据
    // let deviceName = deviceData[data.code]
    // if (!deviceName) {
    const deviceName = await getDeviceList({ type: data.code })
    // }

    loadingRef.value = false
    deviceNameData.value = deviceName
  }

  // 批量配置
  const getOthersData = async (name) => {
    // 当前配置的电表名称
    const deviceId = deviceNameData.value.filter(item => item.name === name)[0].id
    if (dataTypeData.value.length === 0) {
      const dataType = await getDevicePropertyDataTypeList({ deviceId: deviceId })
      dataTypeData.value = dataType
    }
    const dataTypeId = dataTypeData.value[0].id

    const params = {
      dataTypeId,
      deviceId,
    }
    return params
  }
  const schemas: FormSchema[] = [
    {
      label: '数据类型',
      field: 'classifyId',
      component: 'ApiTreeSelect',
      required: true,
      // defaultValue: '1813472054565933056',
      componentProps: ({ formModel, formActionType }) => {
        return {
          api: getClassifyTree,
          labelField: 'classifyName',
          valueField: 'treeId',
          onChange: (e) => {
            formModel.nameList = undefined
          }
        }
      },
    },
    {
      field: 'deviceTypeId',
      label: '设备类型',
      component: 'ApiSelect',
      required: true,
      componentProps: {
        api: getDeviceTypeList,
        labelField: 'name',
        valueField: 'id',
        onChange: handleChangeType
      },
    },
    {
      label: '设备名称',
      field: 'nameList',
      component: 'InputTextArea',
      required: true,
      componentProps: {
        autoSize: { minRows: 10, maxRows: 10 },
      }
    },

    {
      label: '参数类型',
      field: 'calculateType',
      component: 'Select',
      defaultValue: 2,
      componentProps: {
        options: [
          {
            label: '实时值',
            value: 1,
            key: '1',
          },
          {
            label: '增量值',
            value: 2,
            key: '2',
          },
          {
            label: '实时增量值',
            value: 3,
            key: '3',
          },
        ],
      },
      required: true,
    },
    {
      label: '倍率系数',
      field: 'multiple',
      component: 'InputNumber',
      required: true,
      defaultValue: 1,
    },

  ]
  const handleConfig = async () => {
    const { nameList, ...others } = await validate()
    const nameArr = nameList.split('\n')
    let errorNameList: any[] = []
    for (let item of nameArr) {
      try {
        const param = await getOthersData(item)
        const params = {
          ...param,
          ...others,
        }
        await addClassifyDevice(params)
      } catch (err) {
        errorNameList.push(item)
        console.log('%c [ err ]-162', 'font-size:13px; background:pink; color:#bf2c9f;', err, `${item}添加失败`)
      }
    }
    if (errorNameList.length === 0) {
      message.success('全部添加成功')
    } else {
      Modal.confirm({
        title: '错误',
        content: h('div', { style: 'color:red;' }, `${errorNameList.join('、')}添加失败`),

      })
    }
  }
  const [registerForm, { validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas,
    submitFunc: handleConfig,
    submitButtonOptions: {
      text: '配置',
    },
    actionColOptions: {
      span: 23,
    },
  })
</script>
